var express = require("express");
var router = express.Router();
var { AvertisingspaceModel } = require("../db/db");
var Objectid = require("mongodb").ObjectId;

router.get("/advert", async function (req, res) {
  var data = await AvertisingspaceModel.find({});
  res.send({ data: data, code: 200 });
});

router.post("/advert", async function (req, res) {
  let body = req.body;
  await AvertisingspaceModel.create({
    platform: body["platform"],
    name: body["name"],
    call: body["alias"],
    number: body["ad_num"],
    width: body["width"],
    height: body["height"],
    is_sys: body["is_sys"] || '0',
  });
  res.send({ code: 200, message: "创建成功" });
});

router.put("/advert", async function (req, res) {
  let body = req.body;
  let id = Objectid(body["_id"]);
  let data = {
    platform: body["platform"],
    name: body["name"],
    call: body["alias"],
    number: body["ad_num"],
    width: body["width"],
    height: body["height"]
  }
  await AvertisingspaceModel.find({ _id: id }).update({ $set: data });
  res.send({ code: 200 });
});

router.delete("/advert", async function (req, res) {
  var id = Objectid(req.query.id);
  await AvertisingspaceModel.findByIdAndDelete(
    { _id: id },
    function (err, data) {
      if (!err) {
        res.send({ message: "删除成功", code: 200 });
      }
    }
  );
});

module.exports = router;
